<?php

namespace app\admin\controller\customs;

use app\common\controller\Backend;
use Orders\Entity\PushOrderBodyEntity;
use Orders\Entity\PushOrderHeaderEntity;
use Orders\Entity\PushOrderPublicEntity;
use Orders\Service\PushOrderService;
use think\Db;
/**
 * 
 *
 * @icon fa fa-circle-o
 */
class Declaration extends Backend
{

    /**
     * Declaration模型对象
     * @var \app\admin\model\customs\Declaration
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\customs\Declaration;
        $this->view->assign("packagetypecusList", $this->model->getPackagetypecusList());
        $this->view->assign("statusList", $this->model->getStatusList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function commit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        
        $result = false;
        Db::startTrans();
        try {
            $order = $row->toArray();
        
            $publicData = new PushOrderPublicEntity([]);
            $headerData = new PushOrderHeaderEntity($order);
            
            $shop_order_goods = Db::name('shop_order_goods')->where('order_sn',$order['orderNo'])->select();

            $bodydata = [];
            foreach ($shop_order_goods as $key => $value) {
                $shop = Db::name('shop_goods')->where('id',$value['goods_id'])->find();
                $brand = Db::name('shop_brand')->where('id',$shop['brand_id'])->value('name');
                $sku = Db::name('shop_sku_template')->where('id',$value['goods_sku_id'])->value('spec_values');
                $param = [
                    'itemNo'        =>  $value['goods_sn'],
                    'itemName'      =>  $value['title'],
                    'gcode'         =>  $shop['gcode'],
                    'brand'         =>  $brand,
                    'gmodel'        =>  $sku,
                    'qty'           =>  $value['nums'],
                    'unitCus'       =>  $shop['unitCus'],
                    'unitCiq'       =>  $shop['unitCiq'],
                    'qty1'          =>  $shop['qty1'],
                    'Qty2'          =>  $shop['Qty2'],
                    'unitCus1'      =>  $shop['unitCus1'],
                    'unitCus2'      =>  $shop['unitCus2'],
                    'price'         =>  intval($value['price']/$value['nums']),
                    'totalPrice'    =>  $value['price'],
                    'country'       =>  $shop['country'],
                    'usage'         =>  $shop['usage']
                ];
                // echo '<pre>';
                // print_r($param);
                // die();
                $obj   = new PushOrderBodyEntity($param);
                $bodydata[] = $obj->getAllAttributes();
            }
            $obj = new PushOrderService();
            $data = $obj->push($publicData, $headerData, $bodydata);
            if(intval($data['status']) == 1){
                $params = [
                    'status' => 1,
                    'declTime'=>date('Y-m-d H:i:s')
                ];
                $result = $row->allowField(true)->save($params);
                Db::commit();
                
            }else{
                 Db::rollback();
                $this->error($data['detail']);
            }

        
            
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

}
